package cn.yangke.basic.service.impl;

import cn.yangke.basic.constants.BaseConstant;
import cn.yangke.basic.dto.LoginDto;
import cn.yangke.basic.dto.WechatDto;
import cn.yangke.basic.exception.BusinessException;
import cn.yangke.basic.service.ILoginService;
import cn.yangke.basic.util.AjaxResult;
import cn.yangke.basic.util.HttpClientUtils;
import cn.yangke.basic.util.MD5Utils;
import cn.yangke.basic.util.StrUtils;
import cn.yangke.user.domain.Logininfo;
import cn.yangke.user.domain.User;
import cn.yangke.user.domain.Wxuser;
import cn.yangke.user.mapper.LogininfoMapper;
import cn.yangke.user.mapper.UserMapper;
import cn.yangke.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author YangKe
 * @Date 2022/6/18 17:15
 */
@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, Object> account(LoginDto dto) {
        String username = dto.getUsername();
        String password = dto.getPassword();
        Integer type = dto.getType();
        //前端数据空校验
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(type)){
            throw new BusinessException("账号密码不能为空!");
        }
        //根据用户名和type查数据库
        Logininfo logininfo = logininfoMapper.loadByUsernameAndTpye(username,type);
        //查询数据库为null,说明该用户没有注册
        if (logininfo == null){
            throw new BusinessException("该用户不存在,请重新输入正确账户!!");
        }
        //查询到了则校验密码
        //加密加盐
        String salt = logininfo.getSalt();
        String md5Pwd = MD5Utils.encrypByMd5(password + salt);
        //密码不正确
        if(!md5Pwd.equals(logininfo.getPassword())){
            throw new BusinessException("密码错误,请重新输入正确密码!!");
        }

        //密码验证通过后,存储redis
        String token = UUID.randomUUID().toString();
        //储存redis
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        //返回token和logininfo
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        //为了安全,不将密码和盐值加密 传给前端
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        map.put("logininfo",logininfo);
        return map;
    }

    /**
     * 微信三方扫码登录
     * @param dto 前段传递的参数
     * @return
     */
    @Override
    public AjaxResult wechat(WechatDto dto) {
        //接收前段传递的code
        String code = dto.getCode();
        //判断code是否为空
        if(StringUtils.isEmpty(code)){
            throw new BusinessException("微信扫码异常,请稍后重试!!!");
        }
        //获取codeUrl
        String codeUrl = BaseConstant.WeChatConstants.TOKEN_URL
                //替换
                .replace("APPID", BaseConstant.WeChatConstants.APPID)
                .replace("SECRET", BaseConstant.WeChatConstants.SECRET)
                .replace("CODE", code);
        //使用工具类获取响应的json格式字符串
        String tokenStr = HttpClientUtils.httpGet(codeUrl);
        //将json格式的字符串转为JSONObject类的对象
        JSONObject tokenObj = JSONObject.parseObject(tokenStr);
        //获取token
        String accessToken = tokenObj.getString("access_token");
        //获取openID
        String openId = tokenObj.getString("openid");
        //通过openID查询数据库
        Wxuser wxuser = wxuserMapper.loadByOpenId(openId);
        //查询结果不为null且绑定了user_id就直接登录
        if(wxuser != null && wxuser.getUserId() != null){
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
            //密码验证通过后,存储redis
            String token = UUID.randomUUID().toString();
            //储存redis
            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
            //返回token和logininfo
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            //为了安全,不将密码和盐值加密 传给前端
            logininfo.setPassword(null);
            logininfo.setSalt(null);
            map.put("logininfo",logininfo);
            return AjaxResult.getAjax().setResultObj(map);
        }
        //如果查询为null将accessToken和openId传递给前端
        String binderParams = "?accessToken="+accessToken+"&openId="+openId;
        //查询为null则携带参数跳至绑定页面
        return AjaxResult.getAjax().setSuccess(false).setResultObj(binderParams);
    }

    /**
     * 微信扫码登录绑定用户
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> binder(WechatDto dto) {
        String phone = dto.getPhone();
        String password = dto.getPassword();
        String accessToken = dto.getAccessToken();
        String openId = dto.getOpenId();
        String verifyCode = dto.getVerifyCode();
        if (StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(accessToken)
                || StringUtils.isEmpty(openId)) {
            throw new BusinessException("输入框不能为空!");
        }
        if(StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("验证码不能为空!");
        }
        //基于手机号查询
        User user = userMapper.loadByPhone(phone);

        if (user != null) {
            String salt = user.getSalt();
            String passwordTmp = MD5Utils.encrypByMd5(password + salt);
            System.out.println(user.getPassword());
            System.out.println(passwordTmp);
            if(!passwordTmp.equals(user.getPassword())){
                throw new BusinessException("该用户已注册,密码有误,请重新输入密码!");
            }else {
                Wxuser wxuser = wxuserMapper.loadByUserId(user.getId());
                if(wxuser != null){
                    throw new BusinessException("该账号已被其他微信绑定!!");
                }

            }
        }
        Logininfo logininfo = null;
        if(user != null){
            logininfo = logininfoMapper.loadByUserId(user.getId());
        }else {
            user = dto2User(dto);
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }
        //拼接获取微信基本信息的url
        String wxUserUrl = BaseConstant.WeChatConstants.WXUSER_URL
                .replace("ACCESS_TOKEN", dto.getAccessToken())
                .replace("OPENID", dto.getOpenId());
        String wxUserStr = HttpClientUtils.httpGet(wxUserUrl);
        Wxuser wxUser = JSONObject.parseObject(wxUserStr, Wxuser.class);
        //设置userid
        wxUser.setUserId(user.getId());
        //查询出来后新增到wxuser表中
        wxuserMapper.save(wxUser);
        //存储redis
        String token = UUID.randomUUID().toString();
        //储存redis
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        //返回token和logininfo
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        //为了安全,不将密码和盐值加密 传给前端
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        map.put("logininfo",logininfo);
        return map;
    }

    /**
     * 保存用户的登录信息表
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //bean工具类的复制方法,字段名一致的就复制
        BeanUtils.copyProperties(user,logininfo);
        //设置type为前端用户
        logininfo.setType(1);
        return logininfo;
    }

    /**
     * 保存user表
     * @param dto
     * @return
     */
    private User dto2User(WechatDto dto) {
        User user = new User();
        user.setUsername(dto.getPhone());
        user.setPhone(dto.getPhone());
        //获取盐值加密前缀
        String salt = StrUtils.getComplexRandomString(32);
        //使用MD5加密 密码
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }


}
